"""
进程模型
"""
from sqlalchemy import Column, BigInteger, Integer, String, DateTime, Numeric
from sqlalchemy.sql import func
from app.models.base import Base
from typing import Optional

class Process(Base):
    """进程表模型"""
    __tablename__ = 't_processes'
    
    id = Column(BigInteger, primary_key=True, autoincrement=True, comment='进程ID')
    machine_id = Column(Integer, nullable=False, comment='所属机器ID')
    pid = Column(Integer, nullable=False, comment='进程PID')
    name = Column(String(255), nullable=False, comment='进程名称')
    cpu = Column(Numeric(5, 2), nullable=False, default=0.00, comment='CPU使用率(%)')
    memory = Column(Integer, nullable=False, default=0, comment='内存使用(MB)')
    user = Column(String(50), nullable=True, comment='运行用户')
    status = Column(String(20), nullable=True, default='running', comment='进程状态')
    port = Column(String(100), nullable=True, comment='监听端口')
    collected_at = Column(DateTime, nullable=False, default=func.now(), comment='采集时间')
    created_at = Column(DateTime, nullable=False, default=func.now(), comment='创建时间')
    updated_at = Column(DateTime, nullable=False, default=func.now(), onupdate=func.now(), comment='更新时间')
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            'id': self.id,
            'machine_id': self.machine_id,
            'pid': self.pid,
            'name': self.name,
            'cpu': float(self.cpu) if self.cpu is not None else 0.0,
            'memory': self.memory,
            'user': self.user,
            'status': self.status,
            'port': self.port,
            'collected_at': self.collected_at.isoformat() if self.collected_at else None,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }